//html标签替换规则
const tagConverterConfig = {

}

//属性替换规则，也可以加入更多
const attrConverterConfig = {
    'wx:if':{
        key:'v-if',
        value:(str)=>{
            return str.replace(/{{(.*)}}/,'$1')
        }
    },
    'wx:elif': {
        key:'v-else-if',
        value:(str)=>{
            return str.replace(/{{(.*)}}/,'$1')
        }
    },
    'wx:else':{
        key:'v-else',
        value: null,
    },
    'src': {
        key: ':src',
        value: (str)=>{
            return str.replace(/{{(.*)}}/,'$1')
        }
    },
}

// 处理for循环逻辑
const dealForLoop = function(key, attrs, NodeAttrs){
    if (key === 'wx:for') {
        let indexVal = NodeAttrs['wx:for-index']? NodeAttrs['wx:for-index']: 'index'
        let itemVal = NodeAttrs['wx:for-item']? NodeAttrs['wx:for-item']: 'item'

        attrs['v-for'] = NodeAttrs['wx:for'].replace(/{{(.*)}}/,`(${itemVal},${indexVal}) in $1`)
        if (NodeAttrs['wx:key']) {
            attrs[':key'] = NodeAttrs['wx:key'].replace(/{{(.*)}}/,indexVal ==='idx'? '$1': `${itemVal}.$1`)
        }
    }
}

const templateConverter = function(ast){
    for(let i = 0; i<ast.length; i++){
        let node = ast[i]
        //检测到是html节点
        if(node.type === 'tag'){
            //进行标签替换  
            if(tagConverterConfig[node.name]){
                node.name = tagConverterConfig[node.name]
            }
            //进行属性替换
            let attrs = {}
            for(let k in node.attribs){
                let target = attrConverterConfig[k]
                if(target){
                    //分别替换属性名和属性值
                    attrs[target['key']] = target['value'] 
                        ? target['value'](node.attribs[k]) : 
                            node.attribs[k]
                } else if (k === 'wx:for' || k === 'wx:for-item' || k === 'wx:key' || k === 'wx:for-index') {
                    // wx:for wx:for-item wx:key wx:for-index 模块的特殊处理
                    try {
                        dealForLoop(k, attrs, node.attribs)
                    } catch (error) {
                        console.log('parser for loop err', error);
                    }
                } else if (k.indexOf('bind') !== -1){
                    // 将bind统一转换为@
                    let bindKey = k.replace(/bind(.*)/,'@$1');
                    attrs[bindKey] = node.attribs[k];
                } else {
                    attrs[k] = node.attribs[k]
                }
            }
            node.attribs = attrs
        }
        //递归处理
        if(node.children){
            templateConverter(node.children)
        }
    }
    return ast
}
  
module.exports = templateConverter;